<!--用户组管理/index-->
<template>
  <div class="userManagement">
    <searchForm
      label-width="120px"
      :data="searchContent"
      @searchForm="onSubmit"
      @resetForm="onClear"
    />
    <!-- <div class="addBtn">
      <el-button type="primary" icon="el-icon-plus" @click="addUserGroup"
        >新建</el-button
      >
    </div> -->
    <el-editable
      class="el-table"
      :data="tableData"
      height="200"
      v-loading="tableLoading"
      :columns="userManagement"
    >
      <!-- 操作 -->
      <template slot="default-btnGroup" slot-scope="scope">
        <el-button
          size="medium"
          @click.stop="editUserHandler(scope)"
          type="text"
          >编辑</el-button
        >
        <el-button size="medium" @click.stop="toCheck(scope)" type="text"
          >设置</el-button
        >
        <el-button
          size="medium"
          v-show="scope.row.status !== 3"
          @click.stop="updateStatus(scope)"
          type="text"
          >{{ scope.row.status === 1 ? '停用' : '启用' }}</el-button
        >
        <!-- <el-button
          size="medium"
          v-show="scope.row.status !== 2"
          @click.stop="updateStatus(scope, 3)"
          type="text"
          >{{ scope.row.status === 3 ? '解冻' : '冻结' }}</el-button
        > -->
        <el-button
          size="medium"
          v-if="scope.row.ifAdmin != 1"
          @click.stop="handleTableRowDel(scope)"
          type="text"
          >删除</el-button
        >
      </template>
    </el-editable>
    <el-pagination
      class="pagination"
      align="right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="curPage"
      :page-sizes="PAGE_NUMBER"
      :page-size="pageSize"
      :layout="PAGINATION_LAYOUT"
      :total="total"
    />
    <!-- 新增弹框 -->
    <el-dialog
      :title="!isEdit ? '新增用户组' : '修改用户组'"
      :visible.sync="dialogVisibleEdit"
      class="dialog-box"
      width="30%"
      @before-close="closeDialog"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="用户组名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入"
            clearable
            maxlength="16"
          />
        </el-form-item>
        <el-form-item
          label="企业类型"
          prop="companyType"
          v-if="editForm.companyType !== '-1'"
        >
          <el-select v-model="editForm.companyType" placeholder="请选择">
            <el-option
              v-for="item in companyTypeData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="默认选择" prop="defaultConfig">
          <el-select v-model="editForm.defaultConfig" placeholder="请选择">
            <el-option
              v-for="item in defaultConfigData"
              :key="item.val"
              :label="item.lab"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input
            type="textarea"
            v-model="editForm.remark"
            show-word-limit
            maxlength="250"
            placeholder="请输入描述信息"
            rows="4"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.stop="dialogVisibleEdit = false">取消</el-button>
        <el-button
          type="primary"
          @click.stop="submitEditForm"
          :loading="addUserLoading"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ElEditable from '@components/el-editable/door/index.vue'
import searchForm from '@components/search/index.vue'
import {PAGE_NUMBER, PAGINATION_LAYOUT} from '@const/common.js'
import {
  userManagement,
  approveStatus,
  defaultConfigData,
  dialogColumns,
  searchContent
} from './const.js'
import {
  authGroupPageList, // 分页查询用户组
  authGroupUpdateStatusById, // 修改用户组状态
  authGroupSave, // 新增保存用户组状态
  authGroupUpdate, // 编辑用户组状态
  updateStatusById,
  authGroupDeleteById, // 删除用户组
  getAllNoAuthenticationUser,
  authenticationUser,
  commonGetAllEnums // 通用枚举值
} from '@const/api_staffCenter.js'
import {hasIn, cloneDeep} from 'lodash'
export default {
  name: 'UserManagement',
  components: {ElEditable, searchForm},
  data() {
    return {
      approveStatus,
      companyTypeData: [],
      defaultConfigData,
      curPage: 1,
      PAGE_NUMBER, // 页码
      PAGINATION_LAYOUT, // 分页功能
      pageSize: PAGE_NUMBER[0], // 一页的数量
      userManagement, // 表头信息
      total: 0, // 总页数
      searchContent,
      tableData: [], // 表格数据
      // 查询的条件数据
      searchForm: {
        keword: '',
        status: '',
        companyType: ''
      },
      // 编辑用户组
      editForm: {
        id: '',
        name: '',
        remark: '',
        defaultConfig: '',
        companyType: ''
      },
      addUserLoading: false,
      dialogVisibleEdit: false,
      editFormRules: {
        name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        defaultConfig: [{required: true, message: '请选择', trigger: 'blur'}],
        companyType: [
          {required: true, message: '请选择企业类型', trigger: 'blur'}
        ]
      },
      isEdit: false, // 新增true 编辑false
      tableLoading: false,
      userDialog: {
        visible: false,
        loading: false,
        btnLoading: false,
        checkList: [],
        searchKey: '',
        userList: []
      },
      searchQuery: {
        name: '',
        companyType: '',
        status: ''
      }
    }
  },
  created() {
    this.getAllEnums()
    this.search()
    let obj = {
      type: 'btn',
      arr: [
        {
          val: '新建',
          type: 'primary',
          handle: this.addUserGroup
        }
      ]
    }
    this.$store.commit('changeLayoutHandle', obj)
  },
  methods: {
    search() {
      this.tableLoading = true
      this.$axios({
        method: 'GET',
        url: `${authGroupPageList}?page=${this.curPage}&pageSize=${this.pageSize}&name=${this.searchQuery.name}&companyType=${this.searchQuery.companyType}&status=${this.searchQuery.status}`
      })
        .then(res => {
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : {}
          this.tableData = data.content ? data.content : []
          this.total = data.totalElements ? data.totalElements : 0
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    getAllEnums() {
      this.$axios({
        method: 'GET',
        url: commonGetAllEnums
      })
        .then(res => {
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : {}
          this.searchContent[1].options = data.companyTypeEnum
          this.companyTypeData = data.companyTypeEnum
        })
        .finally(() => {})
    },
    // 新建用户组
    addUserGroup() {
      this.isEdit = false
      this.dialogVisibleEdit = true
      this.editForm = {
        id: '',
        name: '',
        remark: '',
        defaultConfig: '',
        companyType: ''
      }
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    closeDialog() {
      this.resetForm()
      this.dialogVisibleEdit = false
    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.editForm.resetFields()
      })
    },
    submitEditForm() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          this.isEdit ? this.updateUser() : this.addUser()
        } else {
          return false
        }
      })
    },
    // 清空查询条件
    onClear() {
      this.searchForm = {name: '', status: '', companyType: ''}
    },
    // 表格修改按钮
    editUserHandler(scope) {
      let data = scope
      this.isEdit = true
      this.dialogVisibleEdit = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
      // this.resetForm()
      data.row.defaultConfig = data.row.defaultConfig.toString()
      for (let item in this.editForm) {
        this.editForm[item] = data.row[item] || ''
      }
    },
    // 确认修改按钮
    updateUser() {
      this.tableLoading = true
      this.addUserLoading = true
      let data = cloneDeep(this.editForm)
      data.defaultConfig = Number(data.defaultConfig)
      this.$axios({
        method: 'post',
        url: authGroupUpdate,
        data: data
      })
        .then(res => {
          if (res.data.code === '0') {
            this.$message.success('操作成功')
            this.dialogVisibleEdit = false
            this.search()
          }
        })
        .finally(() => {
          this.tableLoading = false
          this.addUserLoading = false
        })
    },
    // 新增保存确定按钮
    addUser() {
      this.addUserLoading = true
      let addData = cloneDeep(this.editForm)
      addData.defaultConfig = Number(addData.defaultConfig)
      delete addData.id
      this.$axios({
        method: 'post',
        url: authGroupSave,
        data: {
          ...addData
        }
      })
        .then(res => {
          if (res.data.code === '0') {
            this.$message({message: '操作成功', type: 'success'})
            this.search()
            this.dialogVisibleEdit = false
          }
        })
        .finally(() => {
          this.addUserLoading = false
        })
    },
    toCheck(scope) {
      this.$router.push({
        path: '/systemSetup/userGroupManagement/set',
        query: {
          id: scope.row.id
        }
      })
    },
    // 启用、停用用户
    updateStatus(scope, status) {
      let type = ''
      let curStatus = ''
      if (status === undefined) {
        type = scope.row.status === 1 ? '停用' : '启用'
        curStatus = scope.row.status === 1 ? 2 : 1
      } else {
        type = scope.row.status === 3 ? '解冻' : '冻结'
        curStatus = scope.row.status === 3 ? 1 : 3
      }
      this.$confirm(`是否确认${type}该用户？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableLoading = true
          this.$axios({
            method: 'post',
            url: authGroupUpdateStatusById,
            data: {
              id: scope.row.id,
              status: curStatus
            }
          }).finally(() => {
            this.search()
          })
        })
        .catch(res => {
          console.log(res)
        })
    },
    // 删除row用户组
    handleTableRowDel(scope) {
      this.$confirm('此操作将删除当前用户组, 是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableLoading = true
          this.$axios({
            method: 'POST',
            url: authGroupDeleteById,
            data: {
              id: scope.row.id
            }
          })
            .then(() => {
              this.$message({
                message: '删除成功！',
                type: 'success'
              })
            })
            .finally(() => {
              this.search()
              this.tableLoading = false
            })
        })
        .catch(res => {
          console.log(res)
        })
    },
    onSubmit(data) {
      this.curPage = 1
      data.name = data.name === null ? '' : data.name
      data.companyType = data.companyType === null ? '' : data.companyType
      data.status = data.status === null ? '' : data.status
      this.searchQuery = data
      this.search()
    },
    // 更改页码大小
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.search()
    },
    // 更改当前页
    handleCurrentChange(curPage) {
      this.curPage = curPage
      this.search()
    }
  }
}
</script>
<style lang="less">
.userManagement {
  display: flex;
  flex-direction: column;
  .addBtn {
    margin-bottom: 15px;
  }
  .dialog-box {
    .el-input--medium {
      width: 100%;
    }
    .el-select--medium {
      width: 100%;
    }
  }
  .el-table {
    flex: 1;
  }
  .pagination {
    margin-top: 10px;
  }
  .dialog-new-btn {
    float: right;
    margin-bottom: 10px;
  }
  .add-company-dialog {
    height: 500px;
    display: flex;
    flex-direction: column;
    .dialog-checked-all {
      margin: 16px 0;
    }
    .checkbox-box {
      flex: 1;
      margin-top: 10px;
      margin-right: 10px;
      overflow: auto;
      .el-checkbox {
        display: block;
        margin-left: 0;
      }
    }
  }
}
.el-message--warning {
  z-index: 9999 !important;
}
</style>
